//
//  GridDocumentViewController.swift
//  grid-ios-app
//
//  Created by yanlu on 2024/4/29.
//

import UIKit
import UniformTypeIdentifiers
import SnapKit

class GridDocumentViewController: GridBaseViewController {

    var selectedFileURL: URL?
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        selectBtn.snp.makeConstraints { make in
            make.center.equalToSuperview()
            make.height.equalTo(60)
            make.width.equalTo(200)
        }
        
        saveBtn.snp.makeConstraints { make in
            make.top.equalTo(self.selectBtn.snp.bottom).offset(20)
            make.centerX.equalTo(selectBtn.snp.centerX)
            make.height.equalTo(60)
            make.width.equalTo(200)
        }
    }

    lazy var selectBtn: UIButton = {
        let button = UIButton(type: .custom)
        button.backgroundColor = .clear
        button.setTitle(NSLocalizedString("获取文件", tableName: "GridLocalizable", comment: ""), for: .normal)
        button.setTitleColor(UIColor(hex6: 0xFFFFFF, alpha: 1.0), for: .normal)
        button.titleLabel!.font = Theme.Font.size(12, bold: true)
        button.addTarget(target, action: #selector(self.onClickButton(_:)), for: .touchUpInside)
        button.backgroundColor  = UIColor(hex6: 0x1E90FF)
        button.layer.masksToBounds = true
        button.layer.cornerRadius = 15
        view.addSubview(button)
        return button
    }()
    
    lazy var saveBtn: UIButton = {
        let button = UIButton(type: .custom)
        button.backgroundColor = .clear
        button.setTitle(NSLocalizedString("读取文件", tableName: "GridLocalizable", comment: ""), for: .normal)
        button.setTitleColor(UIColor(hex6: 0xFFFFFF, alpha: 1.0), for: .normal)
        button.titleLabel!.font = Theme.Font.size(12, bold: true)
        button.addTarget(target, action: #selector(self.onClickButton(_:)), for: .touchUpInside)
        button.backgroundColor  = UIColor(hex6: 0x1E90FF)
        button.layer.masksToBounds = true
        button.layer.cornerRadius = 15
        view.addSubview(button)
        return button
    }()
    
    

    lazy var documentPickerVC: UIDocumentPickerViewController = {
        if #available(iOS 14.0, *) {
            let supportedTypes: [UTType] = [UTType.pdf, UTType.png, UTType.jpeg]
            let vc =  UIDocumentPickerViewController.init(forOpeningContentTypes: supportedTypes, asCopy: true)
            vc.delegate = self
            return vc

        } else {
            // Fallback on earlier versions
            let supportedTypes = [

                        "public.data",

                        "com.microsoft.powerpoint.ppt",

                        "com.microsoft.word.doc",

                        "com.microsoft.excel.xls",

                        "com.microsoft.powerpoint.pptx",

                        "com.microsoft.word.docx",

                        "com.microsoft.excel.xlsx",

                        "public.avi",

                        "public.3gpp",

                        "public.mpeg-4",

                        "com.compuserve.gif",

                        "public.jpeg",

                        "public.png",

                        "public.plain-text",

                        "com.adobe.pdf"

                        ]

            let vc =  UIDocumentPickerViewController.init(documentTypes: supportedTypes, in: .import)
            vc.delegate = self
            return vc
        }
    }()

       

    @objc func onClickButton(_ sender: UIButton) {
        if sender == selectBtn {
            self.present(self.documentPickerVC, animated: true)
            
        }else {
            userDefaultsURLGet()
            selectedFileURLGet()
        }
        
    }
    // selectedFileURL 获取
    private func selectedFileURLGet() {
        guard let url = self.selectedFileURL else {
            print("selectedFileURL无数据")
            return
        }
        print("selectedFileURL地址是: \(url)")
        let data = try? Data(contentsOf: url)
        if let data = data {
            // 处理读取到的数据
            print("selectedFileURL读取到的数据: \(data)")
        }
    }
    
    // selectedFileURL 获取
    private func userDefaultsURLGet() {
        guard let url: URL = UserDefaults.standard.url(forKey: "selectedFileURL")  else { return  }
        
        print("userDefaultsURL地址是: \(url)")
        let data = try? Data(contentsOf: url)
        if let data = data {
            // 处理读取到的数据
            print("userDefaultsURL读取到的数据: \(data)")
        }
    }
    
    
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

}

extension GridDocumentViewController: UIDocumentPickerDelegate {
    func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
        //获取授权
        print("授权失败---")

        print("urls : \(urls)")

        // 处理用户选择的文件 URL
        guard let fileUrl = urls.first else { return }

        // 本地保存
        self.selectedFileURL = fileUrl
        // 存储在UserDefaults
        UserDefaults.standard.set(selectedFileURL, forKey: "selectedFileURL")
        UserDefaults.standard.synchronize()
            
    }
    
    func documentPickerWasCancelled(_ controller: UIDocumentPickerViewController) {
            // 用户取消操作
        dismiss(animated: true, completion: nil)
    }
}
